<template>
    <el-card>
        <div slot="header" class="clearfix">
            批次：
            <el-select v-model="selectValue" placeholder="请选择" style="width: 220px; margin-right: 10px">
                <el-option v-for="item in batchOptions" :key="item.id" :label="item.index" :value="item.id">
                    <span style="float: left">{{ item.index }}</span>
                    <el-tag size="mini" type="danger" style="float: right; margin-top: 8px"
                            @click.stop="handleDeleteTag(item)">删除
                    </el-tag>
                </el-option>
            </el-select>
            <el-button type="primary" @click="queryData()">查询</el-button>
            <el-button type="info" style="float: right; margin-left: 10px" @click="exportDataHandle()">导出</el-button>
            <el-popconfirm title="确定要批次结束吗？" @confirm="endBtn()">
                <el-button v-if="dataArr.endFlag==0||dataArr.endFlag==null" type="primary" slot="reference"
                           style="float: right; margin-left: 10px">
                    批次结束
                </el-button>
            </el-popconfirm>
            <el-button v-if="dataArr.endFlag==0 ||dataArr.endFlag==null" type="danger"
                       style="float: right; margin-left: 10px"
                       @click="deadTaobao()">
                死淘数据
            </el-button>
            <el-button type="success" style="float: right; margin-left: 10px"
                       @click="initialData()">初始数据
            </el-button>
        </div>
        <el-descriptions direction="vertical" :column="6" border>
            <el-descriptions-item label="初始入场日期">{{ dataArr.inDate }}</el-descriptions-item>
            <el-descriptions-item label="初始日龄">{{ dataArr.dayAge }}</el-descriptions-item>
            <el-descriptions-item label="初始批次总重">{{ dataArr.totalWeight }}</el-descriptions-item>
            <el-descriptions-item label="初始存栏头数">{{ dataArr.quantity }}</el-descriptions-item>
            <el-descriptions-item label="初始均重"> {{ dataArr.avgWeight }}</el-descriptions-item>
            <el-descriptions-item label="满槽料重">{{ dataArr.materialWeight }}</el-descriptions-item>
            <el-descriptions-item label="累计死淘数量">{{ dataArr.totalNgQuanaity }}</el-descriptions-item>
            <el-descriptions-item label="累计死淘重量" :span="5"> {{ dataArr.totalNgWeight }}</el-descriptions-item>
            <el-descriptions-item label="当前日龄" label-class-name="my-label" content-class-name="my-content">
                {{ dataArr.currentDayAge }}
            </el-descriptions-item>
            <el-descriptions-item label="当前存栏头数" label-class-name="my-label" content-class-name="my-content">
                {{ dataArr.currentQuantity }}
            </el-descriptions-item>
            <el-descriptions-item label="当前均重" label-class-name="my-label" content-class-name="my-content">
                {{ dataArr.currentAvgWeight }}
            </el-descriptions-item>
        </el-descriptions>
        <el-row :gutter="20">
            <el-col :span="6">
                <h3>当前时间：{{ nowDate }}</h3>
            </el-col>
            <el-col :span="12" style="margin-top: 10px">
                <el-button v-if="dataArr.endFlag==0 ||dataArr.endFlag==null" type="primary" @click="checkBtn">日增重
                </el-button>
                <el-button v-if="dataArr.endFlag==0 ||dataArr.endFlag==null" type="primary" @click="feedingClick">
                    日投料
                </el-button>
            </el-col>
        </el-row>
        <el-row :gutter="20" class="date-of-day">
            <el-col :span="9">
                日龄区间：
                <el-input v-model="dayAge1" type="number" placeholder="日龄" style="width: 150px"></el-input>
                ---
                <el-input v-model="dayAge2" type="number" placeholder="日龄" style="width: 150px"></el-input>
            </el-col>
            <el-button type="primary" @click="numberQuery">查询</el-button>
        </el-row>
        <div id="avgFeed" style="width: 100%; height: 300px; margin-bottom: 20px"></div>
        <div id="dayFgs" style="width: 100%; height: 300px; margin-bottom: 20px"></div>
        <el-radio-group v-model="deadTaobaoNum" @change="deadRadio">
            <el-radio label="1">计算死淘</el-radio>
            <el-radio label="0">不计算死淘</el-radio>
        </el-radio-group>
        <div id="dayWeight" style="width: 100%; height: 300px; margin-bottom: 20px"></div>
        <el-radio-group v-model="deadNum" @change="deadValRadio">
            <el-radio label="1">计算死淘</el-radio>
            <el-radio label="0">不计算死淘</el-radio>
        </el-radio-group>
        <div id="dayAvgWeight" style="width: 100%; height: 300px; margin-bottom: 20px"></div>
        <el-dialog title="初始数据" :visible.sync="dialogVisible">
            <el-form :model="dataForm" :rules="dataRules" ref="dataForm" label-width="90px">
                <el-form-item label="入场日期:" prop="inDate">
                    <el-date-picker v-model="dataForm.inDate" type="date" placeholder="入场日期"
                                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="日龄:" prop="dayAge" class="dead-content">
                    <el-input v-model="dataForm.dayAge" placeholder="日龄" class="initial-data"></el-input>
                </el-form-item>
                <el-form-item label="批次总重:" prop="totalWeight" class="dead-content">
                    <el-input v-model="dataForm.totalWeight" placeholder="批次总重" class="initial-data">
                        <template slot="append">kg</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="存栏头数:" prop="quantity" class="dead-content">
                    <el-input v-model="dataForm.quantity" placeholder="存栏头数" class="initial-data">
                        <template slot="append">头</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="满槽料重:" prop="materialWeight" class="dead-content">
                    <el-input v-model="dataForm.materialWeight" placeholder="满槽料重" class="initial-data">
                        <template slot="append">kg</template>
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="dialogHandle('dataForm')">保存</el-button>
            </span>
        </el-dialog>
        <el-dialog title="死淘数据" :visible.sync="deadDialogVisible" width="50%">
            <el-form :model="dieForm" :rules="rules" ref="dieForm" label-width="65px">
                <el-form-item label="日期:" prop="ngDate">
                    <el-date-picker v-model="dieForm.ngDate" type="date" placeholder="选择日期"
                                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="头数:" prop="quantity" class="dead-content">
                    <el-input v-model="dieForm.quantity" placeholder="头数" class="initial-data">
                        <template slot="append">头</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="总重:" prop="totalWeight" class="dead-content">
                    <el-input v-model="dieForm.totalWeight" placeholder="总重" class="initial-data">
                        <template slot="append">kg</template>
                    </el-input>
                </el-form-item>
            </el-form>
            <el-table border :data="tableData" style="width: 100%; margin-top: 20px">
                <el-table-column prop="ngDate" label="日期" align="center">
                </el-table-column>
                <el-table-column prop="quantity" label="头数" align="center">
                </el-table-column>
                <el-table-column prop="totalWeight" label="总重" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button @click="deleteClick(scope.row)" type="primary" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
              <el-button @click="deadDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="footerBtn('dieForm')">保存</el-button>
            </span>
        </el-dialog>
        <el-dialog title="日投料" :visible.sync="dialogFeeding" width="65%">
            <el-form :model="feedingForm" :rules="feedingRules" ref="feedingForm" label-width="120px">
                <el-form-item label="投料日期" prop="feedDate">
                    <el-date-picker v-model="feedingForm.feedDate" type="date"
                                    placeholder="投料日期"
                                    value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="开始称重时间" prop="startWeightTime">
                            <el-date-picker v-model="feedingForm.startWeightTime" type="datetime"
                                            placeholder="开始称重时间"
                                            value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开始均重值" prop="startWeightValue">
                            <el-input placeholder="开始均重值" type="number" v-model="feedingForm.startWeightValue"
                                      clearable
                                      style="width: 220px;margin-right: 10px"></el-input>
                            <el-button type="primary" size="mini" @click="readWeight(0)">读数</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结束称重时间" prop="endFeedTime">
                            <el-date-picker v-model="feedingForm.endFeedTime" type="datetime" placeholder="结束称重时间"
                                            value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束均重值" prop="endWeightValue">
                            <el-input type="number" placeholder="结束均重值" v-model="feedingForm.endWeightValue"
                                      clearable
                                      style="width: 220px;margin-right: 10px"></el-input>
                            <el-button type="primary" @click="readWeight(1)" size="mini">读数</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="feedingForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <el-table :data="dayfeedList" border style="margin-top: 30px">
                <el-table-column prop="feedDate" label="投料日期" align="center"></el-table-column>
                <el-table-column prop="startWeightTime" label="开始称重时间" align="center"
                                 width="150px"></el-table-column>
                <el-table-column prop="startWeightValue" label="开始均重值" align="center"></el-table-column>
                <el-table-column prop="endFeedTime" label="结束称重时间" align="center" width="150px"></el-table-column>
                <el-table-column prop="endWeightValue" label="结束均重值" align="center"></el-table-column>
                <el-table-column prop="diffValue" label="投料重量" align="center"></el-table-column>
                <el-table-column prop="remark" label="备注" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button v-if="isToday(scope.row.feedDate)" @click="dayfeedDelete(scope.row)" type="primary"
                                   size="small">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination :total="total" @currentChange="currentChange" :currentPage="currentPage"
                        @sizeChange="sizeChange">
            </Pagination>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFeeding = false">取 消</el-button>
                <el-button type="primary" @click="beforeFeeding('feedingForm')">保 存</el-button>
            </span>
        </el-dialog>
        <el-dialog title="日增重" :visible.sync="dialogCheck">
            <el-form :model="weightForm" :rules="weightRules" ref="weightForm" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="当日称重日期" prop="weightDate">
                            <el-date-picker v-model="weightForm.weightDate" type="date" placeholder="当日称重日期"
                                            value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="当日值" prop="weightValue">
                            <el-input type="number" placeholder="当日值" v-model="weightForm.weightValue" clearable
                                      style="width: 120px;margin-right: 10px"></el-input>
                            <el-button type="primary" size="small" @click="readWeight()">读数</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input placeholder="备注" v-model="weightForm.remark" clearable type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <el-table :data="dayweightList" border style="margin-top: 30px">
                <el-table-column prop="weightDate" label="当日称重日期" align="center"></el-table-column>
                <el-table-column prop="weightValue" label="当日值" align="center"></el-table-column>
                <el-table-column prop="startWeightDate" label="昨日称重日期" align="center"></el-table-column>
                <el-table-column prop="startWeightValue" label="昨日值" align="center"></el-table-column>
                <el-table-column prop="remark" label="备注" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-popconfirm title="确定删除吗？" @confirm="handleClick(scope.row)">
                            <el-button slot="reference" type="primary" size="small">
                                删除
                            </el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination :total="totals" @currentChange="currentChanges" :currentPage="currentPages"
                        @sizeChange="sizeChanges">
            </Pagination>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogCheck = false">取 消</el-button>
                <el-button type="primary" @click="weightBtn('weightForm')">保 存</el-button>
            </span>
        </el-dialog>
    </el-card>
</template>

<script>
import mixinViewModule from "@/mixins/view-module";
import Pagination from "../../../../components/pagination.vue";
import * as echarts from "echarts";

export default {
    mixins: [mixinViewModule],
    components: {Pagination},
    data() {
        return {
            mixinViewModuleOptions: {
                getDataListURL: "/stock/weight/getLatest",
                exportURL: "/stock/weight/export",
            },
            selectValue: "",
            batchOptions: [],
            deadTaobaoNum: "0", //死淘方法切换
            deadNum: "0",
            dayAge1: "", //搜索日龄
            dayAge2: "", //搜索日龄
            ngFlag: "",
            nowDate: "",
            dataArr: {},
            weightId: "",
            dayweightList: [],
            feedingForm: {
                feedDate: '',
                startWeightTime: '',
                startWeightValue: '',
                endFeedTime: '',
                endWeightValue: '',
                diffValue: '',
                weightId: '',
                remark: ''
            },
            feedingRules: {
                feedDate: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
                startWeightTime: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
                startWeightValue: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
                endFeedTime: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
                endWeightValue: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
            },
            weightForm: {
                weightDate: '',
                weightValue: '',
                weightId: '',
                remark: ''
            },
            weightRules: {
                weightDate: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
                weightValue: [{required: true, message: this.$t('validate.required'), trigger: 'blur'}],
            },
            weightData: [
                {
                    weightDate: '',
                    weightValue: '',
                    startWeightDate: '',
                    startWeightValue: '',
                    weightId: ''
                }
            ],
            dayfeedList: [],
            dayfeedData: [
                {
                    feedDate: '',
                    startWeightTime: '',
                    startWeightValue: '',
                    endFeedTime: '',
                    endWeightValue: '',
                    diffValue: '',
                    weightId: '',
                }
            ],
            totals: 0,
            currentPages: 1,
            sizePages: 10,
            total: 0,
            currentPage: 1,
            sizePage: 10,
            tableData: [],
            deadData: "",
            deadValData: "",
            dialogVisible: false,
            deadDialogVisible: false,
            dialogFeeding: false,
            dialogCheck: false,
            dieForm: {
                ngDate: "",
                quantity: "",
                totalWeight: "",
                weightId: '',
            },
            rules: {
                ngDate: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
                quantity: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
                totalWeight: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
            },
            dataForm: {
                inDate: '',
                dayAge: '',
                totalWeight: '',
                quantity: '',
                materialWeight: '',
                weightId: ''
            },
            dataRules: {
                inDate: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
                dayAge: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
                totalWeight: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
                quantity: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ],
                materialWeight: [
                    {required: true, message: this.$t('validate.required'), trigger: 'blur'}
                ]
            },
            chnNumChar: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
            chnUnitSection: ["", "万", "亿", "万亿", "亿亿"],
            chnUnitChar: ["", "十", "百", "千"],
        }
    },
    created() {
        setInterval(this.gettime, 1000);
    },
    // 销毁
    destroyed() {
        clearInterval(this.gettime);
    },
    mounted() {
        // 当页面打开后，定时器会在5个小时后触发刷新操作。如果页面在5个小时内被关闭，beforeunload 事件会触发，定时器将被清除，避免不必要的刷新操作。
        let timer = setTimeout(() => {
            location.reload();
        }, 5 * 60 * 60 * 1000); // 5个小时，单位为毫秒
        window.addEventListener('beforeunload', () => {
            clearTimeout(timer);
        });

        this.weightAll();
        this.getBasicInformation();
    },
    methods: {
        // 日投料弹窗删除处理
        isToday(date) {
            const today = new Date().toISOString().split('T')[0];
            return date === today;
        },
        SectionToChinese(section) {
            var strIns = "",
                chnStr = "";
            var unitPos = 0;
            var zero = true;
            while (section > 0) {
                var v = section % 10;
                if (v === 0) {
                    if (!zero) {
                        zero = true;
                        chnStr = this.chnNumChar[v] + chnStr;
                    }
                } else {
                    zero = false;
                    strIns = this.chnNumChar[v];
                    strIns += this.chnUnitChar[unitPos];
                    chnStr = strIns + chnStr;
                }
                unitPos++;
                section = Math.floor(section / 10);
            }
            return chnStr;
        },
        NumberToChinese(num) {
            var unitPos = 0;
            var strIns = "",
                chnStr = "";
            var needZero = false;
            if (num === 0) {
                return this.chnNumChar[0];
            }
            while (num > 0) {
                var section = num % 10000;
                if (needZero) {
                    chnStr = this.chnNumChar[0] + chnStr;
                }
                strIns = this.SectionToChinese(section);
                strIns +=
                    section !== 0 ? this.chnUnitSection[unitPos] : this.chnUnitSection[0];
                chnStr = strIns + chnStr;
                needZero = section < 1000 && section > 0;
                num = Math.floor(num / 10000);
                unitPos++;
            }
            return chnStr;
        },
        // 点击查询按钮
        queryData() {
            this.$http.get(`/stock/weight/info/${this.selectValue}`, {
                params: {
                    id: this.selectValue
                }
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.dataArr = res.data;
            });
        },
        // 获取所有批次列表 TODO 确定数据录入顺序 比如 第二次录入时 日期比第一次录入的日期小  看最终需求是以什么为准 如果是以创建时间 那就让后端根据createDate (ORDER BY create_date) 正序排序后返回数据
        weightAll() {
            this.$http.get("/stock/weight/all").then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                console.log(res.data, '获取所有批次列表')
                res.data.forEach((item, index) => {
                    let obj = {
                        id: "",
                        index: "",
                    };
                    obj.id = item.id;
                    // 转中文数字 index 从0开始 需要 + 1
                    obj.index = "第" + this.NumberToChinese(index + 1) + "批次";
                    this.batchOptions.push(obj);
                });
                if (this.batchOptions.length > 0) {
                    this.selectValue = this.batchOptions[0].index
                }
            });
        },
        // 批次下拉删除
        handleDeleteTag(item) {
            this.$confirm("这一批次确定要删除吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$http.delete("/stock/weight", {data: [item.id]}).then(({data: res}) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg);
                    }
                    this.$message.success("删除成功");
                    this.getBasicInformation();
                    window.location.reload();
                }).catch(() => {
                    this.$message.error("删除失败");
                });
            });
        },
        // 导出
        exportDataHandle() {
            this.dataForm.weightId = this.weightId;
            this.exportHandle();
        },
        // 日龄区间查询
        numberQuery() {
            let arr = [];
            arr[0] = this.dayAge1;
            arr[1] = this.dayAge2;

            if (arr[0] == "" && arr[1] == "") {
                this.avgFeedPerPig(null);
                this.dayFg(null);
                this.avgWeightPerPig(null);
                this.avgWeight(null);
            } else {
                this.avgFeedPerPig(arr);
                this.dayFg(arr);
                this.avgWeightPerPig(arr);
                this.avgWeight(arr);
            }
        },
        // 死淘弹窗-删除接口------------------
        deleteClick(row) {
            this.$http.delete("/weight/ng", {data: [row.id]}).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.$message({
                    message: "删除成功",
                    type: "success",
                });
                this.ngPage();
                this.getBasicInformation();
            });
        },
        // 图表公用方法
        getEchartsMethod(arr, data, type) {
            // 1.截取最新的七天      2.搜索时要显示区间
            if (arr != undefined) {
                let xArr = [],
                    xArr1 = [],
                    yArr = [];
                data.forEach((it) => {
                    xArr.push(it.name);
                    xArr1.push(it.subName);
                    yArr.push(it.value);
                });
                if (type === 1) {
                    this.getFeedRatio(xArr, xArr1, yArr);
                } else if (type === 2) {
                    this.getdateRange(xArr, xArr1, yArr);
                } else if (type === 3) {
                    this.getDynamiting(xArr, xArr1, yArr);
                } else if (type === 4) {
                    this.getAverageWeight(xArr, xArr1, yArr);
                }
            } else {
                // 截取倒数7个元素
                const slicedArray = data.slice(-7);
                let xArr = [],
                    xArr1 = [],
                    yArr = [];
                slicedArray.map(it => {
                    xArr.push(it.name);
                    xArr1.push(it.subName);
                    yArr.push(it.value);
                })
                if (type === 1) {
                    this.getFeedRatio(xArr, xArr1, yArr);
                } else if (type === 2) {
                    this.getdateRange(xArr, xArr1, yArr);
                } else if (type === 3) {
                    this.getDynamiting(xArr, xArr1, yArr);
                } else if (type === 4) {
                    this.getAverageWeight(xArr, xArr1, yArr);
                }
            }
        },
        // 统计 - 头均采食量接口----------------------
        avgFeedPerPig(arr) {
            this.$http.post("/weight/dayfeed/avgFeedPerPig", {
                weightId: this.weightId,
                dayAges: arr,
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.getEchartsMethod(arr, res.data, 1)
            });
        },
        // 头均采食量
        getFeedRatio(xArr, xArr1, yArr) {
            var myChart = echarts.init(document.getElementById("avgFeed"));
            var option = {
                legend: {
                    data: ["头均采食量"],
                },
                tooltip: {
                    trigger: "axis",
                },
                xAxis: [
                    {
                        data: xArr,
                        name: "日龄",
                        axisLabel: {
                            formatter: function (value, index) {
                                return value.split('-').splice(1).join('/');
                            }
                        }
                    },
                    {
                        data: xArr1,
                        axisLabel: {interval: 0},
                        position: "bottom", // 很重要，如果没有这个设置，默认第二个x轴就会在图表的顶部
                        offset: 30, // X 轴相对于默认位置的偏移，在相同的 position 上有多个 X 轴的时候有用
                        type: "category", // 坐标轴类型
                        axisTick: {show: false}, // 是否显示坐标轴刻度
                        axisLine: {show: false}, // 是否显示坐标轴轴线
                    },
                ],
                yAxis: {
                    name: "头均采食量(kg)",
                    type: "value",
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                },
                series: [
                    {
                        name: "头均采食量",
                        data: yArr,
                        type: "line",
                        label: {
                            show: true,
                        },
                        lineStyle: {
                            color: "#7b7d7d",
                        },
                    },
                ],
            };
            option && myChart.setOption(option);
        },
        // 统计 - 料肉比接口----------------------
        dayFg(arr) {
            this.$http.post("/weight/dayfeed/dayFg", {
                weightId: this.weightId,
                dayAges: arr,
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.getEchartsMethod(arr, res.data, 2)
            });
        },
        // 料肉比
        getdateRange(xArr, xArr1, yArr) {
            var myChart = echarts.init(document.getElementById("dayFgs"));
            var option = {
                legend: {
                    data: ["料肉比"],
                },
                tooltip: {
                    trigger: "axis",
                },
                xAxis: [
                    {
                        type: "category", // 坐标轴类型
                        data: xArr,
                        name: "日龄",
                        axisLabel: {
                            formatter: function (value, index) {
                                return value.split('-').splice(1).join('/');
                            }
                        }
                    },
                    {
                        data: xArr1,
                        axisLabel: {interval: 0},
                        position: "bottom", // 很重要，如果没有这个设置，默认第二个x轴就会在图表的顶部
                        offset: 30, // X 轴相对于默认位置的偏移，在相同的 position 上有多个 X 轴的时候有用
                        type: "category", // 坐标轴类型
                        axisTick: {show: false}, // 是否显示坐标轴刻度
                        axisLine: {show: false}, // 是否显示坐标轴轴线
                    },
                ],
                yAxis: {
                    name: "料肉比(kg)",
                    type: "value",
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                },
                series: [
                    {
                        name: "料肉比",
                        type: "line",
                        data: yArr,
                        label: {
                            show: true,
                        },
                        lineStyle: {
                            color: "#7b7d7d",
                        },
                    },
                ],
            };
            option && myChart.setOption(option);
        },
        // 统计 - 头均日增重接口----------------------
        avgWeightPerPig(arr) {
            this.$http.post("/weight/dayweight/avgWeightPerPig", {
                weightId: this.weightId,
                ngFlag: this.deadData ? this.deadData : 0,
                dayAges: arr,
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.getEchartsMethod(arr, res.data, 3)
            });
        },
        // 头均日增重
        getDynamiting(xArr, xArr1, yArr) {
            var myChart = echarts.init(document.getElementById("dayWeight"));
            var option = {
                legend: {
                    data: ["头均日增重"],
                },
                tooltip: {
                    trigger: "axis",
                },
                xAxis: [
                    {
                        data: xArr,
                        name: "日龄",
                        axisLabel: {
                            formatter: function (value, index) {
                                return value.split('-').splice(1).join('/');
                            }
                        }
                    },
                    {
                        data: xArr1,
                        axisLabel: {interval: 0},
                        position: "bottom", // 很重要，如果没有这个设置，默认第二个x轴就会在图表的顶部
                        offset: 30, // X 轴相对于默认位置的偏移，在相同的 position 上有多个 X 轴的时候有用
                        type: "category", // 坐标轴类型
                        axisTick: {show: false}, // 是否显示坐标轴刻度
                        axisLine: {show: false}, // 是否显示坐标轴轴线
                    },
                ],
                yAxis: {
                    name: "头均日增重(kg)",
                    type: "value",
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                },
                series: [
                    {
                        name: "头均日增重",
                        data: yArr,
                        type: "line",
                        label: {
                            show: true,
                        },
                        lineStyle: {
                            color: "#7b7d7d",
                        },
                    },
                ],
            };
            option && myChart.setOption(option);
        },
        // 统计 - 头均重接口----------------------
        avgWeight(arr) {
            this.$http.post("/weight/dayweight/avgWeight", {
                weightId: this.weightId,
                ngFlag: this.deadValData ? this.deadValData : 0,
                dayAges: arr,
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.getEchartsMethod(arr, res.data, 4)
            });
        },
        //头均重
        getAverageWeight(xArr, xArr1, yArr) {
            var myChart = echarts.init(document.getElementById("dayAvgWeight"));
            var option = {
                legend: {
                    data: ["头均重"],
                },
                tooltip: {
                    trigger: "axis",
                },
                xAxis: [
                    {
                        data: xArr,
                        name: "日龄",
                        axisLabel: {
                            formatter: function (value, index) {
                                return value.split('-').splice(1).join('/');
                            }
                        }
                    },
                    {
                        data: xArr1,
                        axisLabel: {interval: 0},
                        position: "bottom", // 很重要，如果没有这个设置，默认第二个x轴就会在图表的顶部
                        offset: 30, // X 轴相对于默认位置的偏移，在相同的 position 上有多个 X 轴的时候有用
                        type: "category", // 坐标轴类型
                        axisTick: {show: false}, // 是否显示坐标轴刻度
                        axisLine: {show: false}, // 是否显示坐标轴轴线
                    },
                ],
                yAxis: {
                    name: "头均重(kg)",
                    type: "value",
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                },
                series: [
                    {
                        name: "头均重",
                        data: yArr,
                        type: "line",
                        label: {
                            show: true,
                        },
                        lineStyle: {
                            color: "#7b7d7d",
                        },
                    },
                ],
            };
            option && myChart.setOption(option);
        },
        // 头均日增重----死淘切换按钮
        deadRadio(val) {
            this.deadData = val;
            this.avgWeightPerPig();
        },
        // 头均重----死淘切换按钮
        deadValRadio(val) {
            this.deadValData = val;
            this.avgWeight();
        },
        // 人员基础信息展示接口-----------------
        getBasicInformation() {
            this.$http.get("/stock/weight/getLatest").then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.dataArr = res.data;
                this.weightId = res.data.id;
                this.avgWeightPerPig();
                this.avgWeight();
                this.avgFeedPerPig();
                this.dayFg();
            });
        },
        // 当前时间计算
        gettime() {
            this.nowDate = new Date().toLocaleString();
        },
        //按钮-初始数据录入
        initialData() {
            this.dialogVisible = true;
            this.dataForm = {};
        },
        // 按钮-死淘数据录入
        deadTaobao() {
            this.deadDialogVisible = true;
            this.dieForm = {};
            this.ngPage(); // 调接口-----死淘列表接口
        },
        // 死淘列表接口--------------
        ngPage() {
            this.$http["get"]("/weight/ng/page", {
                params: {weightId: this.weightId},
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.tableData = res.data.list;
            });
        },
        //日投料-保存接口---------------
        beforeFeeding(value) {
            this.$refs[value].validate((valid) => {
                if (valid) {
                    this.feedingForm.weightId = this.weightId
                    this.$http["post"]("/weight/dayfeed", this.feedingForm).then(({data: res}) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg);
                        }
                        this.$message({
                            message: "日投料保存成功",
                            type: "success",
                        });
                        this.dialogFeeding = false;
                        this.feedingForm = {}
                        this.avgFeedPerPig();
                        this.dayFg();
                    });
                } else {
                    return false;
                }
            })
        },
        // 日投料弹窗
        feedingClick() {
            this.dialogFeeding = true;
            this.getDayfeed()
        },
        // 日投料表格接口---------------
        getDayfeed(val) {
            this.$http.get("/weight/dayfeed/page", {
                params: {
                    page: this.currentPage,
                    limit: this.sizePage,
                    weightId: this.weightId
                },
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.dayfeedList = res.data.list;
                this.total = res.data.total;
            });
        },
        // 日投料列表-当前页
        currentChange(val) {
            this.currentPage = val;
            this.getDayfeed();
        },
        // 日投料列表-每页条数
        sizeChange(val) {
            this.sizePage = val;
            this.getDayfeed();
        },
        // 日投料列表删除----
        dayfeedDelete(row) {
            this.$http["delete"]("/weight/dayfeed", {data: [row.id]}).then(({data: res}) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg);
                    }
                    this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                    this.getDayfeed()
                }
            );
        },
        // 死淘数据保存接口----------
        footerBtn(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.dieForm.weightId = this.weightId;
                    this.$http["post"]("/weight/ng", this.dieForm).then(({data: res}) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg);
                        }
                        this.$message({
                            message: "保存成功",
                            type: "success",
                        });
                        this.deadDialogVisible = false;
                        this.dieForm = {};
                        this.getBasicInformation();
                    });
                } else {
                    return false;
                }
            });
        },
        // 初始数据保存接口------
        dialogHandle(value) {
            this.$refs[value].validate((valid) => {
                if (valid) {
                    this.$http.post("/stock/weight", this.dataForm).then(({data: res}) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg);
                        }
                        this.$message({
                            message: "保存成功",
                            type: "success",
                        });
                        this.dialogVisible = false;
                        this.dataForm = {};
                        this.getBasicInformation();
                    });
                } else {
                    return false;
                }
            });
        },
        // 读取数据接口-------------------
        readWeight(val) {
            this.$http["post"]("/stock/weight/startWeight", {
                weightId: this.weightId,
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.$message({
                    message: "读取数据成功",
                    type: "success",
                });
                //0投料前      1投料后
                if (val == 0) {
                    // this.dayfeedData[0].startWeightValue = res.data
                    this.feedingForm.startWeightValue = res.data
                } else if (val == 1) {
                    // this.dayfeedData[0].endWeightValue = res.data
                    this.feedingForm.endWeightValue = res.data
                } else {
                    this.weightForm.weightValue = res.data
                    // this.weightData[0].weightValue = res.data
                }
            });
        },
        // 日增重保存接口---------
        weightBtn(value) {
            this.$refs[value].validate((valid) => {
                if (valid) {
                    this.weightForm.weightId = this.weightId
                    this.$http["post"]("/weight/dayweight", this.weightForm).then(({data: res}) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg);
                        }
                        this.$message({
                            message: "日增重保存成功",
                            type: "success",
                        });
                        this.dialogCheck = false;
                        this.weightForm = {}
                        this.avgWeightPerPig();
                        this.avgWeight();
                    });
                } else {
                    return false
                }
            })
        },
        // 日增重-弹窗
        checkBtn() {
            this.dialogCheck = true;
            this.getWeight(); //日增重列表接口
        },
        //日增重列表接口-------------------
        getWeight() {
            this.$http["get"]("/weight/dayweight/page", {
                params: {
                    page: this.currentPages,
                    limit: this.sizePages,
                    weightId: this.weightId
                },
            }).then(({data: res}) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg);
                }
                this.dayweightList = res.data.list;
                this.totals = res.data.total;
            });
        },
        // 日增重-列表-当前页
        currentChanges(val) {
            this.currentPages = val;
            this.getWeight()
        },
        // 日增重-列表-每页条数
        sizeChanges(val) {
            this.sizePages = val;
            this.getWeight()
        },
        // 日增重-列表-删除接口--------------------
        handleClick(row) {
            this.$http["delete"]("/weight/dayweight", {data: [row.id]}).then(({data: res}) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg);
                    }
                    this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                    this.getWeight();
                }
            );
        },
        // 批次结束按钮----置零
        endBtn() {
            this.$http["post"]("/stock/weight/end", {id: this.weightId}).then(({data: res}) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg);
                    }
                    this.$message({
                        message: "批次已结束！！！",
                    });
                    window.location.reload();
                }
            );
        },
    },
};
</script>

<style>
.date-of-day {
    padding: 15px;
    border-left: 5px solid #009688;
    border-radius: 0 2px 2px 0;
    background-color: #f2f2f2;
    margin-top: 20px;
}

.initial-data {
    width: 220px;
}

.feeding-top {
    margin-top: 10px;
}

.dead-content {
    margin-top: 15px;
}

.my-label {
    background: #0affff;
}

.my-content {
    background: #fde2e2;
}
</style>
